<?php


namespace App\Api\Fcjd;
use App\Domain\User\User as UserDomain;
use App\Domain\Fcjd\Tags as TagsDomain;
use PhalApi\Api;
use PhalApi\Exception\BadRequestException;

/**
 * 非常检单API
 *
 * @author: dogstar <chanzonghuang@gmail.com> 2014-10-04
 */
class Index extends Api
{

    public function getRules()
    {
        return array(
            'login'       => array(
                'mobile'  => array('name' => 'mobile', 'require' => true, 'desc' => 'mobile'),
                'password'  => array('name' => 'password', 'require' => true, 'desc' => 'password'),
                'oaid' => array('name' => 'oaid', 'require' => false, 'desc' => 'oaid'),
                'model' => array('name' => 'model', 'require' => false, 'desc' => 'model'),
            ),
            'Task'      => array(
                'oaid' => array('name' => 'oaid', 'require' => true, 'desc' => 'oaid'),
                'taskNum' => array('name' => 'taskNum', 'require' => false, 'desc' => 'taskNum'),
            ),
            'GetInfo' => array('oaid' => array('name' => 'oaid', 'require' => true, 'desc' => 'oaid'),),
            'Alsms'       => array(),
            'addPhone'    => array(
                'mobile'  => array('name' => 'mobile', 'require' => true, 'desc' => 'mobile'),
                'password'  => array('name' => 'password', 'require' => true, 'desc' => 'password'),
                'username' => array('name' => 'username', 'require' => true, 'desc' => 'username'),
                'smsCode' => array('name' => 'smsCode', 'require' => false, 'desc' => 'smsCode'),
                'mun' => array('name' => 'mun', 'require' => false, 'desc' => 'mun'),
                'wechat_account' => array('name' => 'wechat_account', 'require' => false, 'desc' => 'wechat_account'),
                'wechat_name' => array('name' => 'wechat_name', 'require' => false, 'desc' => 'wechat_name'),
                'alipay_account' => array('name' => 'alipay_account', 'require' => false, 'desc' => 'alipay_account'),
                'alipay_name' => array('name' => 'alipay_name', 'require' => false, 'desc' => 'alipay_name'),
                'idname' => array('name' => 'idname', 'require' => false, 'desc' => 'idname'),
                'idcard' => array('name' => 'idcard', 'require' => false, 'desc' => 'idcard'),
                'z_key' => array('name' => 'z_key', 'require' => false, 'desc' => 'z_key'),
            ),
        );
    }


    /**
     * addPhone
     */

    public function addPhone()
    {
        $mobile = $this->mobile;
        $password = $this->password;
        $username = $this->username;
        // $smsCode = $this->smsCode;
        $mun = $this->mun;
        $wechat_account = $this->wechat_account;
        $wechat_name = $this->wechat_name;
        $alipay_account = $this->alipay_account;
        $alipay_name = $this->alipay_name;
        $idname = $this->idname;
        $idcard = $this->idcard;
        $z_key = $this->z_key;

        //暂时不检测短信
        // $smsCode = \PhalApi\DI()->cache->get($mobile);
        // if ( $smsCode != $this->smsCode  ){
        //     throw new BadRequestException('短信验证码错误');
        // }

        $info = \PhalApi\DI()->notorm->phone_list
                ->where( array('mobile'=> $mobile) )
                ->fetchOne();
        if ($info) {
            throw new BadRequestException('手机号已存在');
        }

        $data = array(
            'mobile' => $mobile,
            'password' => $password,
            'username' => $username,
            'mun' => $mun,
            'wechat_account' => $wechat_account,
            'wechat_name' => $wechat_name,
            'alipay_account' => $alipay_account,
            'alipay_name' => $alipay_name,
            'idname' => $idname,
            'idcard' => $idcard,
            'z_key' => $z_key,
            'create_time' => date("Y-m-d H:i:s",time()),
        );

        if( \PhalApi\DI()->notorm->phone_list->insert($data)){
            return "新增成功";
        }

        throw new BadRequestException('新增失败');
    }
    /**
     * 短信返回
     * @desc 短信返回
     * @return array data 短信返回
     * @exception 400 非法请求，参数传递错误
     */

    public function Alsms()
    {
        $json = file_get_contents('php://input');
        $data = json_decode($json, true);
        \PhalApi\DI()->response->setRet(0);
        \PhalApi\DI()->response->setMsg('成功');
        return $data;
    }


    /**
     * 任务领取
     * @desc 任务领取
     * @return array data 签名url
     * @exception 400 非法请求，参数传递错误
     */
    public function Task()
    {
        // 最简单的处理方式
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *');

        $oaid = $this->oaid;
        $taskNum = $this->taskNum;
        $info = \PhalApi\DI()->notorm->phone_list
                ->where( array('oaid'=> $oaid) )
                ->fetchOne();

        if( empty($info)){
            throw new BadRequestException('不存在此oaid: '. $oaid);
        }

        // 检查是否需要热更新
        // 暂时不热更新
        // if ($info['need_update'] == 1) {
        //     $update_script = \PhalApi\DI()->notorm->phone_app
        //         ->where('script_name', '热更新')
        //         ->fetchOne();
            
        //     if ($update_script) {
        //         // 重置更新状态
        //         \PhalApi\DI()->notorm->phone_list
        //             ->where('oaid', $oaid)
        //             ->update(array(
        //                 'need_update' => 0,
        //                 'update_time' => date("Y-m-d H:i:s",time())
        //             ));
        //         return $update_script;
        //     }
        // }

        //用来更新到设备例表里面
        $ip = $_SERVER['REMOTE_ADDR'];
        $limit = \PhalApi\DI()->cache->get($oaid);
        if ($limit &&  $taskNum > 2 ){
            throw new BadRequestException('正在配置资源，请稍后');
        }
        
   
        if( !$info['task'] ){

            $task_all = \PhalApi\DI()->notorm->phone_app->where('state', 1)->fetchAll();
            $task = array();
            foreach ($task_all as $key => $value) {
                $task[] = $value['id'];
            }

            $save = array(
                'oaid' => $oaid,
                'task' => implode(',', $task)
            );
            
            \PhalApi\DI()->notorm->phone_list->where('id', $info['id'])->update($save);
            $info['task'] = implode(',', $task);
        }else{
            //正常更新一下ip
            \PhalApi\DI()->notorm->phone_list->where('id', $info['id'])->update(array('update_time' => date("Y-m-d H:i:s",time()), 'ip' => $ip));
        }

        $app_list = explode(',', $info['task']);
        function getNextElement($array, $currentElement) {
            // 检查当前元素是否存在于数组中
            if (!in_array($currentElement, $array)) {
                return $array[0]; // 如果元素不在数组中，返回 null
            }
            // 找到当前元素在数组中的索引
            $currentIndex = array_search($currentElement, $array);
            // 计算下一个元素的索引
            $nextIndex = ($currentIndex + 1) % count($array);
            // 返回下一个元素
            return $array[$nextIndex];
        }

        // if( $oaid == "bb15feeb-bdd7-372a-9fdb-7ddbf7df56de"){
        //     return $info;
        // }

        $info['task_n'] = getNextElement($app_list, $info['task_n']);
        //把新task_n更新到数据库
        \PhalApi\DI()->notorm->phone_list->where( array('oaid'=> $oaid) )->update( array('task_n' => $info['task_n']) );
        //取出对应的app脚本
        $task = \PhalApi\DI()->notorm->phone_app->where( array('id'=> $info['task_n']) )->fetchOne();
        //判断取出的脚本是否下架了
        if( !$task || $task['state'] == '0' ){
            //下架了,就强制把任务的task 删掉下架任务, 不过仍然下发该任务,下次不会取到了
            unset($app_list[array_search($info['task_n'], $app_list)]);
            $info['task'] = implode(',', $app_list);

            \PhalApi\DI()->notorm->phone_list->where( array('oaid'=> $oaid) )->update( array('task' => $info['task']) );
            throw new BadRequestException('该任务已下架');
        }

        $app_name = $task['app_name'];
        $hasApp = \PhalApi\DI()->notorm->phone_app_info->where( array('oaid'=> $oaid, 'app_name' => $app_name) )->fetchOne();
        if (!$hasApp){
            \PhalApi\DI()->notorm->phone_app_info->insert(array(
                'oaid' => $oaid,
                'bundle_id' => $info['bundle_id'],
                'app_name' => $app_name,
                'mobile' => $info['mobile'],
                'username' => $info['username'],
                'create_time' => date("Y-m-d H:i:s",time()),
            ));
        }
        
        // 获取游戏标签
        $tagsDomain = new TagsDomain();
        $task['tags'] = $tagsDomain->getTagsByType($task['tag_name']);

        \PhalApi\DI()->cache->set($oaid, 'runing', 60);
        return $task;
    }

    /**
     * 获取信息
     * @desc 获取信息
     * @return array data 获取信息
     * @exception 400 非法请求，参数传递错误
     */
    public function GetInfo()
    {
        // 最简单的处理方式
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *');

        $oaid = $this->oaid;
        $info = \PhalApi\DI()->notorm->phone_list
                ->where( array('oaid'=> $oaid) )
                ->fetchOne();

        if ($info) {
           return array('mobile' => $info['mobile'] , 'password' => $info['password'] );
        }
        
        
    }


    /**
     * 手机登录
     * @desc 手机登录
     * @return array data 签名url
     * @exception 400 非法请求，参数传递错误
     */
    public function login()
    {
        // 最简单的处理方式
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *');

        $mobile = $this->mobile;
        $password = $this->password;
        $oaid = $this->oaid;

        // return array($mobile, $password, $oaid );
        // $data = array('username' => $username, 'password' => $password, 'oaid' => $oaid);

        $info = \PhalApi\DI()->notorm->phone_list
            ->select('id, mobile, is_debug, time_line')
                ->where( array(
                    'mobile'=> $mobile,
                    'password' => $password
                    ))
                ->fetchOne();
        if ($info) {

            if ($info['time_line'] < date('Y-m-d H:i:s', time())) {
                throw new BadRequestException('设备已过期');
            }

            \PhalApi\DI()->notorm->phone_list
                ->where("id", $info['id'])
                ->update(array(
                    'ip' => $_SERVER['REMOTE_ADDR'],
                    'oaid' => $oaid,
                    'update_time'=>date("Y-m-d H:i:s")
                ));
            \PhalApi\DI()->response->setMsg('登录成功');
            return $info;
        } else {
            throw new BadRequestException('用户名或密码错误', 401);
            // return array('code' => 400, 'msg' => '用户名或密码错误');
        }
    }
}